<template>
  <view class="face-auth-container">
    <uni-nav-bar left-icon="back" @clickLeft="goBack" title="人脸认证" />
    
    <view class="content">
      <!-- 相机预览区域 -->
      <view class="camera-container" v-if="!faceCaptured">
        <camera class="camera" device-position="front" flash="off" @error="cameraError"
          :disable-zoom="true" :frame-size="['medium', 'medium']"></camera>
        
        <view class="camera-mask">
          <view class="face-frame"></view>
        </view>
        
        <view class="camera-tips">请将脸部置于框内，保持光线充足</view>
        
        <view class="camera-btn-area">
          <button class="take-photo-btn" @click="takePhoto">点击拍照</button>
        </view>
      </view>
      
      <!-- 照片预览区域 -->
      <view class="photo-container" v-if="faceCaptured">
        <image class="photo-preview" :src="faceUrl" mode="aspectFit"></image>
        
        <view class="btn-area">
          <button class="cancel-btn" @click="retakePhoto">重新拍照</button>
          <button class="confirm-btn" @click="uploadFace">确认上传</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js';

export default {
  data() {
    return {
      faceCaptured: false,
      faceUrl: '',
      cameraContext: null,
      uploadLoading: false
    }
  },
  onLoad() {
    // 创建相机上下文
    this.cameraContext = uni.createCameraContext();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    cameraError(e) {
      console.error('相机错误:', e.detail);
      uni.showToast({
        title: '相机调用失败，请检查权限设置',
        icon: 'none'
      });
    },
    
    takePhoto() {
      if (!this.cameraContext) {
        this.cameraContext = uni.createCameraContext();
      }
      
      uni.showLoading({
        title: '拍照中...',
        mask: true
      });
      
      this.cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          this.faceUrl = res.tempImagePath;
          this.faceCaptured = true;
        },
        fail: (err) => {
          console.error('拍照失败:', err);
          uni.showToast({
            title: '拍照失败，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    
    retakePhoto() {
      this.faceCaptured = false;
      this.faceUrl = '';
    },
    
    uploadFace() {
      if (this.uploadLoading || !this.faceUrl) return;
      
      this.uploadLoading = true;
      uni.showLoading({
        title: '上传中...',
        mask: true
      });
      
      uni.uploadFile({
        url: request.baseUrl + 'property-server/uploadFace',
        filePath: this.faceUrl,
        name: 'face',
        header: {
          'token': uni.getStorageSync('token')
        },
        formData: {
          type: 'face_auth'
        },
        success: (uploadRes) => {
          try {
            const result = JSON.parse(uploadRes.data);
            
            if (result.code === 200) {
              this.saveFaceToDatabase(result.data);
            } else {
              uni.showToast({
                title: result.msg || '上传失败，请重试',
                icon: 'none'
              });
            }
          } catch (e) {
            console.error('解析上传结果失败:', e);
            uni.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('上传失败:', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          this.uploadLoading = false;
          uni.hideLoading();
        }
      });
    },
    
    async saveFaceToDatabase(faceData) {
      try {
        uni.showLoading({
          title: '保存中...',
          mask: true
        });
        
        const res = await request({
          url: 'property-server/saveFaceAuth',
          method: 'POST',
          data: {
            face_base: faceData
          }
        });
        
        if (res.code === 200) {
          uni.showToast({
            title: '人脸认证成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '认证失败，请重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('保存人脸认证信息错误:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
}
</script>

<style scoped>
.face-auth-container {
  background: #f5f6fa;
  min-height: 100vh;
  padding-top: 88rpx;
}
.content {
  padding: 30rpx;
}
.camera-container {
  position: relative;
  width: 100%;
  height: 800rpx;
  background: #000;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.2);
}
.camera {
  width: 100%;
  height: 100%;
}
.camera-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none;
}
.face-frame {
  width: 400rpx;
  height: 400rpx;
  border-radius: 200rpx;
  border: 4rpx dashed #fff;
  box-shadow: 0 0 0 1000rpx rgba(0,0,0,0.4);
}
.camera-tips {
  position: absolute;
  bottom: 160rpx;
  width: 100%;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
}
.camera-btn-area {
  position: absolute;
  bottom: 30rpx;
  width: 100%;
  display: flex;
  justify-content: center;
}
.take-photo-btn {
  width: 240rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #5b9df9 0%, #6ad1f9 100%);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.photo-container {
  width: 100%;
  border-radius: 16rpx;
  background: #fff;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
  overflow: hidden;
  padding: 30rpx;
  box-sizing: border-box;
}
.photo-preview {
  width: 100%;
  height: 700rpx;
  border-radius: 12rpx;
  background: #f0f0f0;
}
.btn-area {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}
.cancel-btn, .confirm-btn {
  width: 45%;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.cancel-btn {
  background: #f0f0f0;
  color: #666;
}
.confirm-btn {
  background: linear-gradient(90deg, #5b9df9 0%, #6ad1f9 100%);
  color: #fff;
}
</style> 